var vehiclesApp = angular.module("vehiclesApp", ["ui.bootstrap","ngRoute","route-segment", "view-segment"]);
//contextPath: Se obtiene desde el controlador y sirve para determinar la url actual
//Dependencias genéricas
vehiclesApp.factory('vehicles', dataFactory);
vehiclesApp.directive('ngJqgrid', ngJqgrid);


modalController = function($scope, $modalInstance, vehicle,guardar,editParams){
   console.log('parent scope',$scope);
    $scope.vehicle = vehicle;
    $scope.guardar = guardar;
    $scope.closeAlert = editParams.closeAlert;
    
    $scope.alerts = editParams.alerts;
    $scope.loading =  editParams.loading;
    $scope.cancel = function() {
        $modalInstance.dismiss('cancel');
    };
}


vehiclesApp.controller("vehiclesController", function($scope, $http, $modal, $log, vehicles) {
    function init(){
        $(window).on('resize', function(event, ui) {
        // Get width of parent container
        var parWidth = $("#gbox_grdVehicles01").parent().parent().width();
        var curWidth = $("#gbox_grdVehicles01").width();
        //console.log("span width " + parWidth + " gridWidth " + gWidth);
        var w = parWidth - 1; // Fudge factor to prevent horizontal scrollbars
        if (Math.abs(w - curWidth) > 2)
        {
            //alert("resize to " + width);
            //console.log("span width " + parWidth + " gridWidth " + curWidth);    
            $("#grdVehicles01").setGridWidth(w);
            // console.log("new width " + w);
        }
    }).trigger('resize');        
    }
    
    init();
    
    $scope.config = {
	url: contextPath + "getVehicles",
	datatype:"json",
	mtype: "POST",
	colNames: ["id", "Nombre", "Tipo", "type", "status", "Volúmen", "Número Económico", "Capacidad", "Marca", "Placas", "Color", "GPS", "Modelo", "Ancho", "Altura", "Profunidad"],
	colModel: [
		{name: "id", width: 40, align: "right", hidden: true},
		{name: "name", index: "name", width: 120},
		{name: "tipo", index: "tipo", width: 80},
		{name: "type", index: "type", width: 80, hidden: true},
		{name: "status", index: "status", width: 80, hidden: true},
		{name: "volume", index: "volume", width: 50, formatter: 'number', formatoptions: {decimalPlaces: 0, suffix: "ft³"}},
		{name: "economic_number", index: "economic_number", width: 30, hidden: true},
		{name: "capacity", index: "capacity", width: 80},
		{name: "trade_mark", index: "trade_mark", width: 80},
		{name: "plate", index: "plate", width: 80, hidden: true},
		{name: "color", index: "color", width: 80, hidden: true},
		{name: "gps", index: "gps", width: 80, hidden: true},
		{name: "model", index: "model", width: 50},
		{name: "width", index: "width", width: 50},
		{name: "height", index: "height", width: 50},
		{name: "deep", index: "deep", width: 50}
	],
	height: 334,
	width:600,
	pager: "#pager",
	rowNum: 10,
	rowList: [10, 20, 30],
	sortname: "name",
	sortorder: "asc",
	viewrecords: true,
	gridview: true,
	autoencode: true,
	caption: "Vehículos",
	altRows: true,
	jsonReader: {
		repeatitems: false,
		id: "id",
		root: function(data) {
			return data[0];
		},
		page: function(data) {
			return data[1][0].page;
		},
		total: function(data) {
			return data[1][0].totalpages;
		},
		records: function(data) {
			return data[1][0].records;
		}
	},
        onSelectRow: function(id){
            $scope.$parent.$apply(function(){
                $scope.$parent.selRow = id;
            })            
        },
        loadComplete: function (data) {            
            $scope.$parent.$apply(function(){
                $scope.$parent.data = data; 
                $scope.$parent.selRow =null
                console.log('loadcomplete');
            });
        }
    }
    
   
    $scope.ref = function(){
        //$scope.apicall('setGridParam',{url:null,datatype:'local', data:$scope.data}).trigger('reloadGrid');
	$scope.gridapi.refresh();
	//console.log($scope.vehicle, $scope.data);
        
	 
	//$scope.selRow = $scope.apicall('getGridParam', 'selrow');
	//rowData = $scope.apicall('getRowData', selRow);
	//alert(rowData.name);
   /*
	$scope.apicall('navGrid', '#pager01', {
		del: true,
		delfunc: function(rowid) {
			alert(rowid);

		},
		addfunc: function() {
			//editar(null, null);
		},
		editfunc: function(rowid) {
			return;
			//rowData = jQuery('#grdVehicles').jqGrid('getRowData', rowid);
			//$('#name').val(rowData.name);
		}
	});*/
    }
    
    $scope.editParams = {}
    $scope.editParams.alerts = [];
    $scope.editParams.loading = false;
    $scope.editParams.closeAlert = function(index) {
        $scope.editParams.alerts.splice(index, 1);
    };
 
    $scope.guardar = function(item, event) { 
        $scope.editParams.loading = true;
        vehicles.save(contextPath + "guardar", $scope.vehicle, {})
                .success(function(data, status, headers, config){
                    //$scope.editParams.loading = false;
                    $scope.editParams.alerts.push({type:"success", msg:"Registro guardado"});                    
                })
                .error(function(data, status, headers, config){
                    alert('Error');
                });
       
    };    
    
    $scope.edit = function(actionType){
        if(actionType==='A'){            
            $scope.vehicle = {};
            $scope.vehicle.id = null;
            $scope.open('lg');
        }else{            
            $scope.vehicle =  $scope.apicall('getRowData', $scope.selRow);
            if($scope.vehicle.id!=null){
                $scope.open('lg');
            }else{
                alert('seleccione primero un registro')
            }
        }        
    }
    
    $scope.del = function(){
        var selRow = jQuery('#grdVehicles').jqGrid('getGridParam', 'selrow');
        var rowData = jQuery('#grdVehicles').jqGrid('getRowData', selRow);
        
        if(rowData.id){            
            var responsePromise = $http.post("Vehicles/eliminar", {id:rowData.id}, {});
            responsePromise.success(function(data, status, headers, config) {
                if(data && data.error){
                    alert( data.error);
                    return;
                }
                $("#grdVehicles").jqGrid('setGridParam', { datatype: 'json' }).trigger('reloadGrid');
            });
            responsePromise.error(function(data, status, headers, config) {
                alert("Submitting form failed!");
            });
        }else{
            alert('seleccione primero un registro')
        }
    }

    $scope.open = function(size) {
        var modalInstance = $modal.open({
            templateUrl: 'edit.html',
            //controller: modalController,
            size: size,
            resolve: {
                vehicle: function() {
                    console.log('Open: vehicle =',$scope.vehicle)
                    return $scope.vehicle;
                },
                guardar: function(){
                    return $scope.guardar;
                },
                editParams:function(){
                    return $scope.editParams;
                }
            },
            scope:$scope
        });

        modalInstance.result.then(function() {
        }, function() {
            $scope.editParams.alerts.splice(0, 1);
            $log.info($scope.vehicle);
        });
    };

});
